
import UIKit

class ListNode {
    var val : Int?
    var next : ListNode?
    init(_ val : Int?) {
        self.val = val
        self.next = nil
    }
}

func addTwoNumbers (_ l1: ListNode? ,_ l2: ListNode? ) -> ListNode?{
    var lN1 = l1;
    var lN2 = l2;
    var result : ListNode?
    var firstResult : ListNode?
    var last : Int = 0;
    while lN1 != nil || lN2 != nil {
        var sum = 0;
        var lNValue1 = 0;
        var lNValue2 = 0;
        if lN1 != nil {
            lNValue1 = lN1?.val as! Int;
        }
        if lN2 != nil {
            lNValue2 = lN2?.val as! Int;
        }
        sum = lNValue1 + lNValue2 + last;
        last = sum / 10;
        sum = sum % 10;
        print("sum = ",sum);
        print("last = ", last);
        if result == nil {
            result = ListNode(sum);
            firstResult = result;
        }else {
            var newResult = ListNode(sum);
            result?.next = newResult;
            result = newResult;
        }
        lN1 = lN1?.next;
        lN2 = lN2?.next;
    }
    if last != 0 {
       var sum = last;
        var newResult = ListNode(sum);
        result?.next = newResult;
        result = newResult;
    }
    return firstResult;
}


let l1: ListNode = ListNode(2);
let l1_1 : ListNode = ListNode(4);
let l1_2 : ListNode = ListNode(3);
l1.next = l1_1;
l1_1.next = l1_2;

let l2 : ListNode = ListNode(5);
let l2_1 : ListNode = ListNode(6);
let l2_2 : ListNode = ListNode(9);
l2.next = l2_1;
l2_1.next = l2_2;

var source : ListNode = addTwoNumbers(l1, l2)!;

print("---> ", source.val);
while source.next != nil {
    source = source.next!;
    print("---> ", source.val);
}

var n1 : Int?
var n2 : Int?
n1 = 2;
n2 = 4;
let sum = n1! + n2!;





